package org.nimi317.web_gis.aspect;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.nimi317.web_gis.context.SecurityContextHolder;
import org.nimi317.web_gis.form.post.Page;
import org.springframework.stereotype.Component;

/**
 * @author thunderobot
 */
@Aspect
@Component
public class PageAspect {

    @Pointcut("execution( * org.nimi317.web_gis.dao.*.*(..))")
    public void page() {

    }

    @Around("page()")
    public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if (joinPoint.getSignature() instanceof MethodSignature signature) {
            Class<?>[] types = signature.getMethod().getParameterTypes();
            for (int i = 0; i < types.length; i++) {
                if (IPage.class.isAssignableFrom(types[i])) {
                    Page page = SecurityContextHolder.getPageSize();
                    Object arg = args[i];
                    if (arg == null) {
                        args[i] = com.baomidou.mybatisplus.extension.plugins.pagination.Page.of(page.getCurrentPage(), page.getPageSize());
                    } else if (ObjectUtils.isNotEmpty(page) && arg instanceof IPage<?> iPage) {
                        iPage.setPages(page.getCurrentPage());
                        iPage.setSize(page.getPageSize());
                    }
                }
            }
        }
        return joinPoint.proceed(args);
    }

    @Before("@annotation(org.nimi317.web_gis.annotation.Page)")
    public void beforePage(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            if (arg instanceof Page page) {
                SecurityContextHolder.setPageSize(page);
            }
        }
    }
}
